# coding:utf-8
import time
from io import BytesIO

import QRcodeOper
from fraMail import mail_conf

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

from fralog.FraLog import Fralog

"""
发送邮件主模块

用户支付成功后应发邮件通知客户
邮件内容包括：
订单号
支付金额
购买时间
购买内容

报告链接(动态生成)
"""


class FraMail(object):
    def __init__(self):
        super(FraMail).__init__()
        self.host = mail_conf.host
        self.port = mail_conf.port
        self.username = mail_conf.username + '@' + mail_conf.prefix
        self.passwd = mail_conf.passwd
        self.timeout = mail_conf.timeout
        self.log = Fralog().getFileLog()
        self.mysign = ''
        self._setConnected(False)

    def _setConnected(self, value):
        self.connected = value

    def login(self):

        if self.connected:
            self.log.info('E-Mail已登录，避免重复验证，以提升效率')
            return

        if self.port == 465:
            self.smtp = smtplib.SMTP_SSL(host=self.host, timeout=self.timeout)
        elif self.port == 25:
            self.smtp = smtplib.SMTP(host=self.host, timeout=self.timeout)

        try:
            self.log.info('connect to {0} in port {1}'.format(self.host, self.port))
            self.smtp.connect(self.host, port=self.port)
            self.log.info("Connect SMTP OK")
            self.smtp.login(self.username, self.passwd)
            self.mysign = "<华院数据>" + mail_conf.username + '@' + mail_conf.prefix
            self.log.debug("登录服务器成功")
            self.log.debug("我的签名:" + self.mysign)
            self._setConnected(True)
        except Exception as e:
            self.log.error(e.args)

    def logout(self):
        if self.connected:
            self.log.info('邮件发送完毕或无任务，退出登陆')
            self.smtp.close()
            self._setConnected(False)

    def send(self, sendto, content, title='Fra+'):
        try:
            msg = MIMEText(content, _subtype="html", _charset="gb2312")
            msg['Subject'] = title
            msg['From'] = self.username
            msg['to'] = sendto
            # self.log.info(msg.as_string())
            self.smtp.sendmail(self.username, sendto, msg.as_string())
            self.log.info('邮件发送成功')
        except smtplib.SMTPServerDisconnected:
            self.log.info('已断开......')
            raise smtplib.SMTPServerDisconnected('Reconnect.....')
        except Exception as e:
            self.log.error(e.args)

    def send_file(self, filename, to, title, msg):
        """
        发送附件
        :param filename: 要发送的文件的路径 
        :param to 收件人
        :param title 邮件标题
        :param msg 附加的文本消息
        :return: 
        """
        message = MIMEMultipart()
        message['From'] = Header(self.username, "utf-8")
        # message['To'] = Header(to, "utf-8")
        subject = title
        message['Subject'] = Header(subject, "utf-8")

        text_msg = MIMEText(msg)
        message.attach(text_msg)
        #
        # 如果文件名不为空，添加附件
        if filename is not None:
            attr = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8')
            attr['Content-Type'] = 'application/octet-stream'
            attr["Content-Disposition"] = 'attachment; filename="%s"' % (filename)
            message.attach(attr)
        self.smtp.sendmail(self.username, to, message.as_string())

    def send_qrfile(self, filename, to, title, msg):
        """
        发送附件
        :param filename: 要发送的文件的路径
        :param to 收件人
        :param title 邮件标题
        :param msg 附加的文本消息
        :return:
        """
        message = MIMEMultipart()
        message['From'] = Header(self.username, "utf-8")
        # message['To'] = Header(to, "utf-8")
        subject = title
        message['Subject'] = Header(subject, "utf-8")

        text_msg = MIMEText(msg)
        message.attach(text_msg)
        #
        # 如果文件名不为空，添加附件
        if True:
            attr = MIMEText(filename, 'base64', 'utf-8')
            attr['Content-Type'] = 'application/octet-stream'
            attr["Content-Disposition"] = 'attachment; filename="qrlink.jpg"'
            message.attach(attr)
        self.smtp.sendmail(self.username, to, message.as_string())

    def send_file_func(self, filename, to, title):
        """
        发送附件
        :param filename:
        :return:
        """
        current_time = time.localtime(time.time())
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        message = MIMEMultipart()
        message['From'] = Header("华院数据", "utf-8")
        message['To'] = Header("客户", "utf-8")
        subject = "李宁问卷中旺旺号_" + timestr
        message['Subject'] = Header(subject, "utf-8")

        if filename is not None:
            attr = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8')
            attr['Content-Type'] = 'application/octet-stream'
            attr["Content-Disposition"] = 'attachment; filename="%s"' % (timestr + filename)
            message.attach(attr)
        self.smtp.sendmail(self.username, to, message.as_string())


if __name__ == "__main__":
    # mail = FraMail()
    # # msg = '<h1>您刚刚购买了Fra+</h1>'
    # # msg += '<p>again</p>'
    # # mail.send('xiaodong.yang@unidt.com',msg)
    # mail.login()
    # mail.send_file(None, 'xiaodong.yang@unidt.com', 'Hello', '这是附件')
    # mail.send('466426129@qq.com', "您好,请24小时内点击激活链接\r\n http://www.baidu.com \r\n谢谢! ")
    # mail.login()
    # mail.send('466426129@qq.com', "您好,请24小时内点击激活链接\r\n http://www.baidu.com \r\n谢谢! ")
    str = '123'
    img = QRcodeOper.returnqrcode(str)
    msstream = BytesIO()
    img.save(msstream, "jpeg")
    img.close()
    mail = FraMail()
    mail.login()
    # send_file(filename, to, title, msg):
    mail.send_qrfile(filename=msstream.getvalue(), to=['fei.wang@huaat.net', '466426129@qq.com'], title='问卷二维码图片链接',
                     msg='这是二维码图片链接邮件,请查看附件图片')
